<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="请假类型" prop="type">
        <el-input
          v-model="queryParams.type"
          placeholder="请输入请假类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['business:vacationRule:query']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:vacationRule:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:vacationRule:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:vacationRule:del']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:vacationRule:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="holidayList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="适用区域" align="center" prop="regionName" />
      <el-table-column label="归属门店" align="center" prop="storeName" />
      <el-table-column label="休假类型" align="center" prop="type" />
      <el-table-column
        label="角色"
        align="center"     :show-overflow-tooltip="true"
        prop="effectiveRoles"
        width="150"
      >
        <template slot-scope="{ row }">
          {{
            (row.effectiveRoles &&
              row.effectiveRoles
                .map((ele) => ele.effectiveRoleName)
                .join(",")) ||
            ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="请假周期" align="center" prop="period">
        <template slot-scope="{ row }">
          {{ row.period == 1 ? "年" : row.period == 2 ? "月" : "" }}
        </template>
      </el-table-column>
      <el-table-column
        label="周期休息次数"
        align="center"
        prop="frequency"
        width="120"
      />
      <el-table-column
        label="每次连休天数"
        align="center"
        prop="everyTimeDays"
        width="120"
      />

      <!-- <el-table-column label="每年休假天数" align="center" prop="applyInAdvance" /> -->
      <el-table-column
        label="提前申请天数"
        align="center"
        prop="applyInAdvance"
        width="120"
      />
      <el-table-column label="上架" align="center" prop="isInitiate">
        <template slot-scope="scope">
          <span
            :style="{ color: scope.row.isInitiate ? '#808080' : '#FF5733' }"
            >{{ scope.row.isInitiate == "1" ? "上架" : "下架" }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="创建人"   align="center"  prop="createBy" />
      <el-table-column label="创建时间"   align="center"  prop="createTime" />
      <el-table-column label="修改人"   align="center"  prop="updateBy" />
      <el-table-column label="修改时间"   align="center"  prop="updateTime" />

      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        class-name="small-padding fixed-width"
        width="250px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:vacationRule:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload2"
            @click="handleGround(scope.row, (isInitiate = 1))"
            v-hasPermi="['business:vacationRule:listing']"
            :disabled="scope.row.isInitiate === '1'"
            >上架</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleGround(scope.row, (isInitiate = 2))"
            v-hasPermi="['business:vacationRule:offShelf']"
            :disabled="scope.row.isInitiate === '2'"
            >下架</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:vacationRule:del']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改休假规则对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="600px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="区域" prop="regionId">
          <el-select clearable v-model="form.regionId" @change="changeRegion">
            <!-- multiple -->

            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="适用门店" prop="storeId">
          <el-select
            clearable
            v-model="form.storeId"
            @change="changeStore"
            :disabled="form.regionId == null"
          >
            <el-option
              v-for="(item, index) of store"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="effectiveRoles">
          <el-select
            clearable
            v-model="form.effectiveRoles"
            multiple
            collapse-tags
          >
            <el-option
              v-for="(item, index) of holidayRoleS"
              :key="index"
              :label="item.roleName"
              :value="item.roleId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="请假类型" prop="type">
          <el-input
            v-model="form.type"
            placeholder="请输入请假类型"
            style="width: 222px"
          />
        </el-form-item>
        <el-form-item label="请假周期" prop="period">
          <el-select clearable v-model="form.period">
            <el-option
              v-for="(item, index) of periodList"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="周期休假天数" prop="frequency">
          <el-input
            v-model="form.frequency"
            placeholder="请输入周期休假天数"
            style="width: 222px"
          />
        </el-form-item>
        <el-form-item label="连续休假天数" prop="everyTimeDays">
          <el-input
            v-model="form.everyTimeDays"
            placeholder="请输入连续休假天数"
            style="width: 222px"
          />
        </el-form-item>
        <el-form-item label="提前申请天数" prop="applyInAdvance">
          <el-input
            v-model="form.applyInAdvance"
            placeholder="请输入提前天数"
            style="width: 222px"
          />
        </el-form-item>
        <!-- <el-form-item label="每月休假次数" prop="everyMonthTimes">
          <el-input v-model="form.everyMonthTimes" placeholder="请输入包间名称" />
        </el-form-item> -->
        <!-- <el-form-item label="提前请假天数" prop="applyInAdvance">
          <el-input v-model="form.applyInAdvance" placeholder="请输入包间名称" />
        </el-form-item> -->

        <el-form-item label="上架" prop="isInitiate">
          <el-select clearable v-model="form.isInitiate">
            <el-option
              v-for="(item, index) of List"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listrule,
  getrule,
  deliterule,
  addrule,
  updaterule,
  listMemberRegion,
  listMemberStore,
  getHolidayRole,
} from "@/api/system/personnelMatters/vacationRule";

export default {
  name: "Holiday",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 休假规则表格数据
      holidayList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        userName: null,
        numbe: null,
        type: null,
        job: null,
        phoneNumber: null,
        regionId: null,
        regionName: null,
        storeId: null,
        storeName: null,
        type: null,
        state: null,
        beginTime: null,
        endTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      List: [
        {
          key: "1",
          value: "上架",
        },
        {
          key: "2",
          value: "下架",
        },
      ],
      store: [],
      region: [],
      holidayRoleS: [],
      periodList: [
        {
          key: 1,
          value: "年",
        },
        {
          key: 2,
          value: "月",
        },
      ],
    };
  },
  created() {
    this.getList();
    this.listregion();
    this.getRoleList();
    listMemberStore().then((res) => {
      console.log(res, 333);
      this.store = res.data.map((rItem) => {
        return {
          key: rItem.id,
          value: rItem.storeName,
        };
      });
    });
  },
  methods: {
    getRoleList() {
      getHolidayRole().then((res) => {
        this.holidayRoleS = res.rows;
      });
    },
    listregion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    changeRegion(value) {
      const selectedOption = this.region.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      console.log(`Selected Key: ${selectedKey}`);
      console.log(`Selected Value: ${selectedValue}`);
      this.form.regionName = selectedValue;
      listMemberStore({ regionId: value }).then((res) => {
        this.store = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },
    changeStore(value) {
      const selectedOption = this.store.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      console.log(`Selected Key: ${selectedKey}`);
      console.log(`Selected Value: ${selectedValue}`);
      this.form.storeName = selectedValue;
      console.log(this.form.storeName, 555);
    },
    // 上下架
    handleGround(row, isInitiate) {
      const params = {
        id: row.id,
        isInitiate: isInitiate,
      };
      this.$confirm(
        `此操作将${isInitiate === 1 ? "上架" : "下架"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updaterule(params).then((res) => {
            this.$message({
              type: "success",
              message: `${isInitiate === 1 ? "上架" : "下架"}成功!`,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消上下架",
          });
        });
    },
    /** 查询休假规则列表 */
    getList() {
      this.loading = true;
      listrule(this.queryParams).then((response) => {
        this.holidayList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        userName: null,
        numbe: null,
        job: null,
        phoneNumber: null,
        regionId: null,
        regionName: null,
        storeId: null,
        storeName: null,
        type: null,
        state: null,
        beginTime: null,
        endTime: null,
        createBy: null,
        createTime: null,
        updateTime: null,
        period: null,
        frequency: null,
        applyInAdvance: null,
        effectiveRoles: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加休假规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getrule(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.form.effectiveRoles =
          (response.data.effectiveRoles &&
            response.data.effectiveRoles.map(
              (ele) => ele.effectiveRoleId - 0
            )) ||
          [];
        this.title = "修改休假规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let list = this.form.effectiveRoles || [];
          let effectiveRoles = list.map((ele) => {
            let index = this.holidayRoleS.findIndex(
              (item) => item.roleId == ele
            );
            let effectiveRoleName =
              index > -1 ? this.holidayRoleS[index].roleName : "";
            return {
              effectiveRoleId: ele - 0,
              effectiveRoleName,
            };
          });
          if (this.form.id != null) {
            updaterule({ ...this.form, effectiveRoles }).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addrule({ ...this.form, effectiveRoles }).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return deliterule(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/system/rule/export",
        {
          ...this.queryParams,
        },
        `休假规则_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style>
.dialog-footer {
  text-align: center;
}
</style>
